uint8_t currentChannel = 0x00;
uint8_t byteNumber = 0x00;
static char isFirstByte = true; // to bypass the NACK flag for the first byte in a transaction
ISR(TWI0_TWIS_vect)
{
if (TWI0.SSTATUS & TWI_COLL_bm) {
//I2C_0_collision_callback();
return;
}
if (TWI0.SSTATUS & TWI_BUSERR_bm) {
//I2C_0_bus_error_callback();
return;
}
if ((TWI0.SSTATUS & TWI_APIF_bm) && (TWI0.SSTATUS & TWI_AP_bm)) {
//I2C_0_address_callback();
// Write ACK callback here because otherwise the master won't receive an ACK when selecting the address
byteNumber == 0;
TWI0.SCTRLB = TWI_ACKACT_ACK_gc | TWI_SCMD_RESPONSE_gc;
isFirstByte = true;
return;
}
if (TWI0.SSTATUS & TWI_DIF_bm) {
if (TWI0.SSTATUS & TWI_DIR_bm) {
// Master wishes to read from slave
if (!(TWI0.SSTATUS & TWI_RXACK_bm) || isFirstByte) {
// Received ACK from master or First byte of transaction
isFirstByte = false;
//I2C_0_read_callback();
TWI0.SCTRLB = TWI_ACKACT_ACK_gc | TWI_SCMD_RESPONSE_gc;
} else {
// Received NACK from master
// Reset module
TWI0.SSTATUS |= (TWI_DIF_bm | TWI_APIF_bm);
TWI0.SCTRLB = TWI_SCMD_COMPTRANS_gc;
}
} else // Master wishes to write to slave
{
uint8_t data = TWI0.SDATA;
if(byteNumber == 0){ // Receive register/channel
if(data < 9){
currentChannel = data;
}else{
// Channel invalid. write NACK
TWI0.SCTRLB = TWI_ACKACT_NACK_gc | TWI_SCMD_RESPONSE_gc;
}
}else if(byteNumber == 1){ // received PWM value
wanted_led_output_values[currentChannel*2] = data;
}else if(byteNumber == 2){ // received fade speed
wanted_led_output_values[(currentChannel*2)+1] = data;
}else{
// Unknown data
TWI0.SCTRLB = TWI_ACKACT_NACK_gc | TWI_SCMD_RESPONSE_gc;
}
byteNumber++;
//USART_write(TWI0.SDATA);
//I2C_0_write_callback();
}
return;
}
// Check if STOP was received
if ((TWI0.SSTATUS & TWI_APIF_bm) && (!(TWI0.SSTATUS & TWI_AP_bm))) {
//I2C_0_stop_callback();
byteNumber == 0;
TWI0.SCTRLB = TWI_SCMD_COMPTRANS_gc;
return;
}
}